package com.xbchzh.clifford.action;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.xbchzh.clifford.base.BaseAction;
import com.xbchzh.clifford.domain.Order;
import com.xbchzh.clifford.utils.WeixinConst;

/**
 * 微信通信
 * 
 * @author David Huang /weixin/weixinAction*
 */

@Controller
@Scope("prototype")
public class WeixinAction extends BaseAction<Order> {

	private static final long serialVersionUID = 1L;

	/**
	 * 我们在“基本配置”上提交信息后，微信服务器将发送GET请求到填写的服务器地址URL上。 这个方法就是我们要填写的URL，这个方法要完成：
	 * 1）将token、timestamp、nonce三个参数进行字典序排序 
	 * 2）将三个参数字符串拼接成一个字符串进行sha1加密
	 * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	 * 
	 * @return
	 * @throws Exception
	 *             /weixin/weixinActioncheck
	 */
	public String check() throws Exception {

		HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");

		//1）将token、timestamp、nonce三个参数进行字典序排序 
		String[] str = { WeixinConst.TOKEN, timestamp, nonce };
		Arrays.sort(str); // 字典序排序
		String bigStr = str[0] + str[1] + str[2];
		
		//2 ）将三个参数字符串拼接成一个字符串进行sha1加密
		String digest = "";
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
            crypt.update(bigStr.getBytes("UTF-8"));
            digest = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		//3) 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		if (!"".equals(digest)&&digest.equals(signature)) {
			ActionContext.getContext().getSession().put("commonText", echostr);
        }
		else{
			ActionContext.getContext().getSession().put("commonText", "fuck you! 居然冒充微信来验证！");
		}
		return "commonText";
	}

	private String byteToHex(byte[] hash) {
		Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
	}

}
